package com.pandora.loan.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author developer
 */
public class HttpUtil {

    public static String sendPost(String type, int port, String host, String method, Map<String, String> headers, Map<String, String> params){
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(type+"://"+host+":"+port+method);

        for(Map.Entry<String, String> e : headers.entrySet()){
            postMethod.setRequestHeader(e.getKey(), e.getValue());
        }
        JSONObject jsonObject = new JSONObject();
        for(Map.Entry<String, String> p : params.entrySet()){
            jsonObject.put(p.getKey(), p.getValue());
        }
        try {
            RequestEntity re = new StringRequestEntity(jsonObject.toString(),"application/json", "UTF-8");
            postMethod.setRequestEntity(re);
            int statusCode = httpClient.executeMethod(postMethod);
            String res = new String(postMethod.getResponseBodyAsString().getBytes("UTF-8"));
            if(statusCode != MagicConst.NUM_200){
                return null;
            }
            return res;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] argv){
        Map<String, String> headers = new LinkedHashMap<>();
        headers.put("Authorization", Constants.QA_AUTHORIZATION_TOKEN);
        headers.put("Content-Type", "application/json");
        Map<String, String> params = new LinkedHashMap<>();
        params.put("mobile", "15822098640");
        params.put("id_card_no", "120109198809103538");
        params.put("name", "王磊");
        params.put("bank_card_no", "6228480020282573417");
        String resp = HttpUtil.sendPost("http", 80, Constants.CERTIFICATION_HOST, Constants.CERTIFICATION_METHOD, headers, params);
        System.out.println(resp);
    }
}
